/* 
* Filename:  main.c
* Creation date:      06.05.2013
* Originator:    Anton Babushkin (Antony.Babushkin@gmail.com)
* Revision history:
*   V1.01 06.05.2013 - Creation
* Description:
*   Main file for Yet Another PWM project sine wave demo.
 */

 /* Include header files */
#include <io.h>
#include <math.h>
#include "sys/alt_stdio.h"
#include "PWMModule/PWMModule.h"// Include PWM module codes

#define PWM0_BASE_ADDR					0x20000000// Base address of PWM0 module

#define pi 3.141592654
#define FREQ	0.8*1e7// in Hz
#define PWM_COUNT	10// define count of PWM modules to be used

int main()
{ 
	int t = 0;
	double y;
	double Freq = FREQ;
	double Phase = 0.2;
	int dt = 1;
	uint8_t i;

	pwm_module_t * PWMModule[PWM_COUNT] = {
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*0)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*1)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*2)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*3)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*4)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*5)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*6)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*7)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*8)),
			((pwm_module_t *)(PWM0_BASE_ADDR + sizeof(pwm_module_t)*9))};


	alt_putstr("Hello from Nios II PWM Demo!\n");

	for(i=0; i<PWM_COUNT; i++)
	{
		// Set parameters
		PWMModule[i]->Control.b.OutEnable = 0;
		PWMModule[i]->DivFactor = 0;
		PWMModule[i]->PulseLen = 0;
		PWMModule[i]->PeriodLen = 0;
		PWMModule[i]->Control.b.DivReset = 1;
		PWMModule[i]->Control.b.PwmReset = 1;
	}

	for(i=0; i<PWM_COUNT; i++)
	{
		PWMModule[i]->Control.b.OutEnable = 1;// Enable PWM Out

		PWMModule[i]->DivFactor = 0;// Set parameters
		PWMModule[i]->PulseLen = 50;
		PWMModule[i]->PeriodLen = 99;
		alt_printf("PWM Module # %x\tEnabled\n", i);
	}

	while(1)
	{
		for(i=0; i<PWM_COUNT; i++)// For each PWM module (0 to 9)
		{
			// Calculate Pulse Length normalized value (scaled between 0 to 1)
			y = (sin(2*pi*Freq*t + Phase*i) + 1.0)/2.0;
			// Calculate exact value and load into Pulse Length register (Period Length - amplitude)
			PWMModule[i]->PulseLen = (uint32_t)(((double)(PWMModule[i]->PeriodLen)) * y);
			// Wait for cycle completion - for synchronization
			while(!PWMModule[i]->Control.b.Done);
			t+=dt;// Increment time
		}
	}

	return 0;
}
